﻿namespace BEGDC.CC.Web.EZVisit.Common
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Security.Principal;
    using ASBCC.Utility;
    using BL.Common;
    using ExcelTool;
    using Utility.Castle;
    using Utility.Extensions;
    using Workflow;

    #endregion

    public partial class EZVRequestCustomerImport : BasePage
    {
        private string ApplicationSessionKey
        {
            get
            {
                return this.Request.QueryString["sn"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //using (WindowsImpersonationContext context = UploadUtility.NetworkImpersonateUser())
                //{
                    string fileName = ExcelImporter.UploadExcelFile(this.edt_UploadGifts);

                    var excelData = ExcelImporter.Import(fileName, string.Empty);

                    // context.Undo();

                    string error;

                    if (!ValidateExcelFileSchema(excelData, out error))
                    {
                        this.Response.Write("<script type=\"text/javascript\">alert('" + error + "');</script>");
                        return;
                    }

                    if (excelData.Rows.Count > 0)
                    {
                        this.UpdateCustomerSession(excelData);
                        this.Response.Write(@"<script type=""text/javascript"">window.close();window.returnValue='reload';</script>");
                    }
                    else
                    {
                        this.Response.Write("<script type=\"text/javascript\">alert('Cannot find any customers information in the Excel worksheet (Sheet1)');</script>");
                    }
                //}
            }
            catch (Exception ex)
            {
                this.Response.Write("<script type=\"text/javascript\">alert('" + ex.Message.Replace("'", "") + "');</script>");
            }
        }

        private void UpdateCustomerSession(DataTable data)
        {
            var dt = this.Session[EZVRequestCustomer.SessionKey + this.ApplicationSessionKey] as DataTable;

            if (dt == null)
            {
                return;
            }

            int rowId = dt.Rows.Count + 1;

            var values = new string[10];

             var utility = (IUtility)AppContainer.Instance[ServiceConst.UtilityService];

            foreach (DataRow row in data.Rows)
            {
                values[0] = row.Field<string>("Customer Name in CN_客户姓名(中文)");
                values[1] = row.Field<string>("Customer Name in PinYin_客户姓名(拼音)");
                values[2] = row.Field<string>("Customer Company in CN_ 客户单位(中文)");
                values[3] = row.Field<string>("Customer Company in EN_客户单位(英文)");
                values[4] = row.Field<string>("Customer Title in CN_ 客户职务(中文)");
                values[5] = row.Field<string>("Customer Title in EN_客户职务(英文)");
                values[6] = row.Field<string>("Gender_性别");
                values[7] = row.Field<string>("Responsibility_职责");
                values[8] = row.Field<string>("Remark_注释");

                bool valid = true;

                for (int i = 0; i < 6; i++)
                {
                    if (values[i].IsNotNullOrWhiteSpace())
                    {
                        continue;
                    }

                    valid = false;
                    break;
                }

                if (valid)
                {
                    int gender = values[6].IsNotNullOrWhiteSpace() && values[6].Equals("Female (女)") ? 0 : 1;

                    string condition = string.Format("RowId <>{0} and IsEnabled=1 and NameCN='{1}' and CompanyCN='{2}' and TitleCN='{3}' and Gender={4}", rowId, values[0].Trim(), values[2].Trim(), values[4].Trim(), gender);

                    // Already exists?
                    if (dt.Select(condition).Length > 0)
                    {
                        continue;
                    }

                    var responsibility = utility.GetDicItem(values[7].Trim(), DicType.RESPONSIBILITY);

                    var customerRow = dt.NewRow();

                    customerRow["NameCN"] = values[0].Trim();
                    customerRow["NameEN"] = values[1].Trim();
                    customerRow["CompanyCN"] = values[2].Trim();
                    customerRow["CompanyEN"] = values[3].Trim();
                    customerRow["TitleCN"] = values[4].Trim();
                    customerRow["TitleEN"] = values[5].Trim();
                    customerRow["Gender"] = gender;
                    customerRow["Responsibility"] = responsibility.Id;
                    customerRow["ResponsibilityText"] = responsibility.DicItemKey;
                    customerRow["Remark"] = values[8];
                    customerRow["IsExisted"] =  CISFlag.NotExisted;
                    customerRow["CreateAt"] = DateTime.Now;
                    customerRow["CreateBy"] = this.UserInfo.NameEN;
                    customerRow["IsEnabled"] = true;

                    rowId++;

                    dt.Rows.Add(customerRow);
                }
            }

            this.Session[EZVRequestCustomer.SessionKey + this.ApplicationSessionKey] = SetRowID(dt);
        }

        private static DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1]["RowId"] = i.ToString();
                }
            }

            return table;
        }

        #region Excel Data Validation

        private static bool ValidateExcelFileSchema(DataTable dt, out string error)
        {
            error = string.Empty;

            if (dt == null)
            {
                error = "Failed to import customers information from Excel worksheet (Sheet1).";
                return false;
            }

            if (dt.Columns.IndexOf("Customer Name in CN_客户姓名(中文)") < 0)
            {
                error = "Column \"Customer Name in CN 客户姓名(中文)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Customer Name in PinYin_客户姓名(拼音)") < 0)
            {
                error += "Column \"Customer Name in PinYin 客户姓名(拼音)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Customer Company in CN_ 客户单位(中文)") < 0)
            {
                error += "Column \"Customer Company in CN 客户单位(中文)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Customer Company in EN_客户单位(英文)") < 0)
            {
                error += "Column \"Customer Company in EN 客户单位(英文)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Customer Title in CN_ 客户职务(中文)") < 0)
            {
                error += "Column \"Customer Title in CN 客户职务(中文)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Customer Title in EN_客户职务(英文)") < 0)
            {
                error += "Column \"Customer Title in EN 客户职务(英文)\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Gender_性别") < 0)
            {
                error += "Column \"Gender 性别\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Responsibility_职责") < 0)
            {
                error += "Column \"Responsibility 职责\" was not found in worksheet (Sheet1)\\n";
            }

            if (dt.Columns.IndexOf("Remark_注释") < 0)
            {
                error += "Column \"Remark 注释\" was not found in worksheet (Sheet1)\\n";
            }

            return error.Length == 0;
        }

        #endregion
    }
}